package com.mtz.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 煜赜
 * @date 2018/12/19 0019 上午 10:25
 */
@Component
@ServletComponentScan
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "tokenFilter")
public class TokenFilter implements Filter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final long timeout = 60*30;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getServletPath();
//        System.out.println("path:"+path);

        if (path.startsWith("/user/server/login") || path.startsWith("/excel/download") ||
            path.startsWith("/swagger-ui.html")   || path.startsWith("/swagger-resources") || path.startsWith("/webjars") || path.startsWith("/v2")) {

            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = request.getHeader("token");
        if (token == null) {
            token = "";
        }

        // 去redis里查
        String tokenValue = redisTemplate.opsForValue().get(token);
        if (StringUtils.isEmpty(tokenValue)) {
            ((HttpServletResponse) servletResponse).setStatus(403);
            log.warn("【登录校验】Redis中查不到token={}",token);
            return;
        }
        redisTemplate.expire(token, timeout, TimeUnit.SECONDS);
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
